/**
 * 请求服务类
 */
import axios from '../network-config/axios.config';
import ResponseModel from '../model/response.model';
import {RequestConfigModel} from "@/common/model/request.config.model";
import {callbackify} from "util";
import RequestModel from "@/common/model/request.model";

/**
 * 导出请求服务类
 */
export default class service {

//接口调用的公共方法
    public static request({headers, method, url, data, params, responseType, progress, cancel}: RequestConfigModel): Promise<ResponseModel> {
        return new Promise((resolve, reject) => {
            axios({
                headers,
                method,
                url,
                data,
                params,
                responseType,
                onUploadProgress: progressEvent => {//返回提交进度回调
                    if (progress) {
                        return progress(((progressEvent.loaded / progressEvent.total) * 100).toFixed(0));
                    }
                },
                cancelToken: new axios.CancelToken((canceler) => {// 取消请求
                    if (cancel) {
                        return cancel(canceler);
                    }
                })
            }).then(res => {
                const result = new ResponseModel();
                Object.assign(result, res.data);
                return resolve(result);
            }).catch(err => {
                return reject(err);
            })
        });
    }

    /**
     * 公共方法（需要多包一层data的接口）
     */
    public static post(url: string, data?: any, headers?: any, progress?: Function, cancel?: Function): Promise<ResponseModel> {
        return this.request({
            data: data instanceof RequestModel ? data : new RequestModel(data),
            method: 'POST',
            url,
            headers,
            progress,
            cancel
        })
    }

    public static get(url: string, data?: any, progress?: Function, cancel?: Function): Promise<ResponseModel> {
        if (data instanceof RequestModel) {
            return this.request({params: data, method: 'GET', url, progress, cancel});
        } else {
            return this.request({params: new RequestModel(data), method: 'GET', url, progress, cancel});
        }
    }
}

